﻿using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Web;
using System.Data;
using System.Xml;


namespace TOD
{
    [Guid("55981492-0874-4638-85bd-c3830c89cfba")]
    public class TOD : System.Web.UI.WebControls.WebParts.WebPart
    {

        
        public TOD()
        {
            this._SiteName = "";
            this._ListName = "";
            this._ViewName = "";
            this._TODTitle = "Title";
            this._TODDesc = "Tip";
            this._RSSFeedURL = "";
            this._ImagePath = "";
            this._BackGroundColor = "";
            this._ExtraText = 0;
            this.ConcatText = "";
        }






        protected string _TODDesc = "Tip";
        protected string _BackGroundColor = "";
        protected bool _EveryDay;
        protected string _RSSFeedURL = "";
        protected string _ImagePath = "Lightbulb";
        protected string _ListName = "";
        protected int _ExtraText;
        protected string _SiteName = "";
        protected string _TODTitle = "Title";
        protected string _ViewName = "";
                private string ConcatText = "";
        
        protected override void OnPreRender(EventArgs e)
        {
            bool flag = false;
            try
            {
                flag = WebPartManager.GetCurrentWebPartManager(this.Page) != null;

            }
            catch (Exception exception)
            {
                this.ConcatText = this.ConcatText + "Web Part Manager:" + exception.Message;
            }
            base.SetPersonalizationDirty();
        
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            string strJavascript = "<script type='text/javascript' language='javascript'>";
            strJavascript += "function HandleMore(){var value1=document.getElementById('todhiddenfull').value;document.getElementById('TODText').innerHTML=value1+'<a href=# onclick=javascript:HandleLess() >(less)</a>';}";
            strJavascript += "function HandleLess(){var value2=document.getElementById('todhiddenless').value;document.getElementById('TODText').innerHTML=value2+'... <a href=# onclick=javascript:HandleMore() >(more)</a>';}</script>";
            this.Page.RegisterStartupScript("Desc", strJavascript);
            int num = this._ExtraText;
            bool flag = num < 0;
            if (flag)
            {
                num = -num;
            }
            string str = "";
            int num2 = 0;
            string str2 = "";
            if (!string.IsNullOrEmpty(this._BackGroundColor))
            {
                str2 = " bgcolor='" + this._BackGroundColor + "'";
            }
            if (!string.IsNullOrEmpty(this._RSSFeedURL))
            {

                XmlDataDocument document = new XmlDataDocument();
                try
                {
                    if (flag)
                    {
                        writer.Write("<br>Feed URL=" + this._RSSFeedURL);
                    }
                    document.Load(this._RSSFeedURL);
                    XmlNodeList elementsByTagName = document.GetElementsByTagName("item");
                    string str7 = "";
                    Random random = new Random(DateTime.Now.Millisecond);
                    if (flag)
                    {
                        writer.Write("<br>Nbr of posts=" + elementsByTagName.Count);
                    }
                    int num9 = 0;
                    int num10 = 0;
                    if (!this._EveryDay)
                    {
                        num10 = random.Next(elementsByTagName.Count);
                    }
                    else
                    {
                        DateTime time2 = new DateTime(0x708, 1, 1);
                        num10 = ((int)DateTime.Today.Subtract(time2).TotalDays) % elementsByTagName.Count;
                    }
                    if (flag)
                    {
                        writer.Write("<br>selected Post=" + num10);
                    }
                    foreach (XmlNode node in elementsByTagName)
                    {
                        num9++;
                        if (num10 == (num9 - 1))
                        {
                            if (node["title"] != null)
                            {
                                if (flag)
                                {
                                    writer.Write(string.Concat(new object[] { "<br>", num9, ":", node["title"].InnerText }));
                                }
                                if (node["link"] != null)
                                {
                                    str7 = str7 + "<a href='" + node["link"].InnerText + "' target=_blank>";
                                }
                                str7 = str7 + "<strong>" + node["title"].InnerText + "</strong>";
                                if (node["link"] != null)
                                {
                                    str7 = str7 + "</a>";
                                }
                            }
                            if (node["description"] != null)
                            {
                                string str8 = node["description"].InnerText.Trim();
                                if (str8.Substring(0, 3) != "<p>")
                                {
                                    str7 = str7 + "<br />";
                                }
                                str7 = str7 + str8;
                            }
                            this.ConcatText = this.ConcatText + "<table width=100% cellspacing=0 cellpadding=8><tr" + str2 + ">";
                            if (!string.IsNullOrEmpty(this._ImagePath))
                            {
                                string webResourceUrl = this._ImagePath;
                                if (this._ImagePath.ToLower() == "lightbulb")
                                {
                                    webResourceUrl = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), "TOD.bulb.gif");
                                }
                                this.ConcatText = this.ConcatText + "<td valign=top><img src='" + webResourceUrl + "' style='margin-top:0px' border=0></td>";
                            }
                            this.ConcatText = this.ConcatText + "<td valign=top style='padding-left:10px;'>" + str7 + "</td></tr></table>";
                            break;
                        }
                    }
                    goto Label_0CBB;
                }
                catch (Exception exception2)
                {
                    this.ConcatText = "Unable to load RSS feed: " + exception2.Message;
                    goto Label_0CBB;
                }
            }
            SPSite site = SPContext.Current.Site;
            
                SPWeb web = null;
                
                    try
                    {
                        if (!string.IsNullOrEmpty(this._SiteName))
                        {
                            web = site.OpenWeb(this._SiteName);
                        }
                        else
                        {
                            web = SPContext.Current.Web;
                        }
                        if (!string.IsNullOrEmpty(this._ListName))
                        {
                            if (flag)
                            {
                                this.ConcatText = this.ConcatText + "<br>List=" + this._ListName;
                            }
                            SPList list2 = null;
                            SPListItemCollection items = null;
                            try
                            {
                                Random random2;
                                list2 = web.Lists[this._ListName];
                                if (!string.IsNullOrEmpty(this._ViewName))
                                {
                                    try
                                    {
                                        SPView view = list2.Views[this._ViewName];
                                        items = list2.GetItems(view);
                                        goto Label_06DB;
                                    }
                                    catch
                                    {
                                        writer.Write("Sharepoint View not found: " + this._ViewName);
                                        return;
                                    }
                                }
                                items = list2.Items;
                            Label_06DB:
                                random2 = new Random(DateTime.Now.Millisecond);
                                int count = items.Count;
                                if (flag)
                                {
                                    this.ConcatText = this.ConcatText + "<br>Nbr of items=" + count;
                                }
                                if (count > 0)
                                {
                                    string ConcatText;
                                    int num12 = 0;
                                    if (!this._EveryDay)
                                    {
                                        num12 = random2.Next(count);
                                    }
                                    else
                                    {
                                        DateTime time3 = new DateTime(0x708, 1, 1);
                                        num12 = ((int)DateTime.Today.Subtract(time3).TotalDays) % count;
                                    }
                                    if (flag)
                                    {
                                        this.ConcatText = this.ConcatText + "<br>Selected item=" + num12;
                                    }
                                    bool flag2 = false;
                                    if (!string.IsNullOrEmpty(this._BackGroundColor))
                                    {
                                        flag2 = list2.Fields.ContainsField(this._BackGroundColor);
                                    }
                                    SPListItem item = items[num12];
                                    string str10 = "";
                                    string str11 = "";
                                    if (flag2)
                                    {
                                        str2 = "";
                                        if (item[this._BackGroundColor] != null)
                                        {
                                            str2 = " bgcolor='" + item[this._BackGroundColor].ToString() + "'";
                                        }
                                    }
                                    this.ConcatText = this.ConcatText + "<table width=100% cellspacing=0 cellpadding=8><tr" + str2 + ">";
                                    if (!string.IsNullOrEmpty(this._ImagePath))
                                    {
                                        string str13 = this._ImagePath;
                                        if (this._ImagePath.ToLower() == "lightbulb")
                                        {
                                            str13 = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), "TOD.bulb.gif");
                                        }
                                        else if (!str13.Contains("."))
                                        {
                                            try
                                            {
                                                str13 = "";
                                                if (item[this._ImagePath] != null)
                                                {
                                                    str13 = item[this._ImagePath].ToString();
                                                }
                                                int num14 = str13.IndexOf(",");
                                                if (num14 >= 0)
                                                {
                                                    str13 = str13.Substring(0, num14);
                                                }
                                            }
                                            catch
                                            {
                                                writer.Write(this._ImagePath + ": Picture column not found!<br>");
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(str13))
                                        {
                                            ConcatText = this.ConcatText;
                                            this.ConcatText = ConcatText + "<td valign=top>" + str10 + "<img src='" + str13 + "' style='margin-top:0px' border=0>" + str11 + "</td>";
                                        }
                                    }
                                    ConcatText = this.ConcatText;
                                    this.ConcatText = ConcatText + "<td valign=top style='padding-left:10px;'>" + str10 + "<strong>" + item[this._TODTitle].ToString() + "</strong>" + str11 + "<br />";
                                    try
                                    {
                                        if (item[this._TODDesc] != null)
                                        {
                                            string str14 = item[this._TODDesc].ToString().Replace("&nbsp;", " ").Replace("  ", " ");
                                            
                                            
                                            char[] separator = new char[] { ' ' };
                                            string[] strArray2 = str14.Split(separator);
                                            if (strArray2.Length > num)
                                            {
                                                str14 = "";
                                                for (int i = 0; i < num; i++)
                                                {
                                                    str14 = str14 + strArray2[i] + " ";
                                                }
        
                                                    ConcatText = str14;
                                                    string strfull= " <input id = 'todhiddenfull' type ='hidden' value = '" + item[this._TODDesc].ToString() + "' />";
                                                    string strless = " <input id = 'todhiddenless' type ='hidden' value = '" + str14 + "' />";
                                                    str14 = "<span id='TODText'>" + ConcatText + "...&nbsp;" + str10 + "<a href='#' onclick='javascript:HandleMore();' >(more)</a></span>" + str11;
                                                    str14 += strfull + strless;
        
                                            }
                                            this.ConcatText += str14;
                                        }
                                    }
                                    catch
                                    {
                                        this.ConcatText = "<br>Abstract Column not specified or not found:" + this._TODDesc;
                                    }
                                    this.ConcatText = this.ConcatText + "</td></tr></table>";
                                }
                                else
                                {
                                    this.ConcatText = "The specified Sharepoint List is empty!";
                                    
                                }
                            }
                            catch (Exception exception3)
                            {
                                if (flag)
                                {
                                    this.ConcatText = this.ConcatText + "<br>Error:" + exception3.Message;
                                }
                                this.ConcatText = this.ConcatText + "<br>Sharepoint List not found:" + this._ListName;
                            }
                        }
                        else
                        {
                            this.ConcatText = "No Sharepoint List defined!";
                        }
                    }
                    catch (Exception)
                    {
                        this.ConcatText = "<br>Site not found:" + this._SiteName;
                    }
                Label_0CBB:
                    writer.Write(this.ConcatText);
                    if (str != "")
                    {
                        writer.Write("<br>" + str);
                    }
            
        }
        [WebBrowsable(true), Personalizable, WebDisplayName("Thought/Tip Text Field Name"), WebDescription("Enter the name of the Thought/Tip text column")]
        public string AbstractField
        {
            get
            {
                return this._TODDesc;
            }
            set
            {
                this._TODDesc = value;
            }
        }

        [WebDisplayName("Background Color"), WebDescription("Web Part background color"), WebBrowsable(true), Personalizable]
        public string BGColor
        {
            get
            {
                return this._BackGroundColor;
            }
            set
            {
                this._BackGroundColor = value;
            }
        }

        [Personalizable, WebBrowsable(true), WebDisplayName("Show new thought/tip every day"), WebDescription("leave unticked if you want a new thought/tip on every page refresh")]
        public bool EveryDay
        {
            get
            {
                return this._EveryDay;
            }
            set
            {
                this._EveryDay = value;
            }
        }

        [Personalizable, WebDisplayName("RSS Feed URL"), WebDescription("Enter the URL of the desired RSS Feed"), WebBrowsable(true)]
        public string FeedURL
        {
            get
            {
                return this._RSSFeedURL;
            }
            set
            {
                this._RSSFeedURL = value;
            }
        }

        [WebDisplayName("Image URL"), Personalizable, WebDescription("Enter the name of the Image URL"), WebBrowsable(true)]
        public string ImageURL
        {
            get
            {
                return this._ImagePath;
            }
            set
            {
                this._ImagePath = value;
            }
        }

        

        [WebBrowsable(true), WebDisplayName("List Name"), Personalizable, WebDescription("Enter the name of the list")]
        public string ListName
        {
            get
            {
                return this._ListName;
            }
            set
            {
                this._ListName = value;
            }
        }

        [Personalizable, WebDisplayName("Max number of words displayed"), WebDescription("Limit the number of words displayed"), WebBrowsable(true)]
        public int More
        {
            get
            {
                return this._ExtraText;
            }
            set
            {
                this._ExtraText = value;
            }
        }

        [Personalizable, WebBrowsable(true), WebDisplayName("Site Name"), WebDescription("Enter the name of the site")]
        public string SiteName
        {
            get
            {
                return this._SiteName;
            }
            set
            {
                this._SiteName = value;
            }
        }

        [WebDescription("Enter the name of the Title column"), WebBrowsable(true), WebDisplayName("Thought/Tip Title Field Name"), Personalizable]
        public string TitleField
        {
            get
            {
                return this._TODTitle;
            }
            set
            {
                this._TODTitle = value;
            }
        }

        [WebBrowsable(true), WebDisplayName("View Name"), WebDescription("Enter the name of the List View (optional)"), Personalizable]
        public string ViewName
        {
            get
            {
                return this._ViewName;
            }
            set
            {
                this._ViewName = value;
            }
        }
    }
}
